package com.mb.search.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mb.common.pojo.Product;
import com.mb.search.mapper.IndexMapper;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class IndexSercviceImpl implements IndexSercvice{

    @Autowired
    private TransportClient client;

    @Autowired(required = false)
    private IndexMapper indexMapper;
    //json转化
    private static final ObjectMapper mapper=new ObjectMapper();

    @Override
    public void doIndex() {

        IndicesAdminClient indices = client.admin().indices();
        //判断神奇盒子索引文件是否存在
        IndicesExistsResponse response = indices.prepareExists("sqhz").get();
        if (response.isExists()){
            //存在直接使用
            return;
        }

        //创建映射
        XContentBuilder mapping = null;
        try {
            mapping = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("productName").field("type", "text").field("analyzer", "ik_max_word").endObject()
                    .startObject("productPrice").field("type", "double").endObject()
                    .startObject("productImage").field("type", "keyword").field("ignore_above", 256).endObject()
                    .startObject("productNum").field("type", "integer").endObject()
                    .startObject("productId").field("type", "keyword").field("ignore_above", 36).endObject()
                    .startObject("productCategory").field("type", "keyword").endObject()
                    .startObject("productDescription").field("type", "text").field("analyzer", "ik_max_word").endObject()
                    .endObject()
                    .endObject();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("io流异常");
        }
        //pois：索引名   cxyword：类型名（可以自己定义）
        PutMappingRequest putmap = Requests.putMappingRequest("sqhz").type("product").source(mapping);
        //创建索引
        client.admin().indices().prepareCreate("sqhz").execute().actionGet();
        //为索引添加映射
        client.admin().indices().putMapping(putmap).actionGet();
        //查询所有商品
        List<Product> productList = indexMapper.selectAllProducts();
        String productJson = null;
        for (Product product : productList) {
            try {
               productJson = mapper.writeValueAsString(product);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                System.out.println("转换json失败");
            }
            IndexRequestBuilder requestBuilder = client.prepareIndex("sqhz", "product", product.getProductId());

            requestBuilder.setSource(productJson).get();
        }
    }
}
